package com.motu.monstercity.server.game.web;

import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message.Builder;
import com.googlecode.protobuf.format.JsonFormat;
import com.motu.monstercity.protocol.CmdEnum;
import com.motu.monstercity.protocol.CmdEnum.EnumCmdID;
import com.motu.monstercity.server.game.verticle.MainVerticle;
import com.motu.vertx.module.utility.mysql.MysqlClient;
import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import com.motu.vertx.module.utility.webtool.BaseWebHandler;
import com.motu.vertx.module.utility.webtool.SearchCondition;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.client.WebClient;

import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

public class ProtocolmonitorhttpHandler extends BaseWebHandler{
	public static void add(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		addToTable(routingContext, MysqlClient.getServerPool(), "protocol_monitor_http", json);
	}

	public static void update(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		updateToTable(routingContext, MysqlClient.getServerPool(), "protocol_monitor_http", json);
	}

	public static void getone(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		getFromTable(routingContext, MysqlClient.getServerPool(), "protocol_monitor_http");

	}
	public static void delete(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		deleteFromTable(routingContext, MysqlClient.getServerPool(), "protocol_monitor_http");
	}

	public static void search(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		List<SearchCondition> scList = new ArrayList<SearchCondition>();
		scList.add(new SearchCondition("cmd_code", "=", null, null));
		searchFromTable(routingContext, MysqlClient.getServerPool(), json, "protocol_monitor_http", scList);
	}
	
	public static void search_data(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		HttpServerResponse response = routingContext.response();
		JsonArray params1 = new JsonArray();
		String whereStr = "";
		if (json.containsKey("cmd_code")) {
			whereStr += " and cmd_code =? ";
			params1.add(json.getInteger("cmd_code"));
		}
		if (json.containsKey("stime")) {
			whereStr += " and add_time >= ? ";
			params1.add(TimeUtils.getTimeStrIntValue(json.getString("stime")));
		}
		if (json.containsKey("etime")) {
			whereStr += " and add_time <= ? ";
			params1.add(TimeUtils.getTimeStrIntValue(json.getString("etime")));
		}
		
		String sql1 = "select count(1) as total from protocol_monitor_data_http where 1=1 " + whereStr + ";";
		String sql2 = "select * from protocol_monitor_data_http where 1=1 " + whereStr + " order by add_time desc limit ?, ?;";
		JsonArray params2 = params1.copy();
		int pageNo = json.getInteger("pageNo");
		int pageSize = json.getInteger("pageSize");
		int start = pageNo*pageSize;
		params2.add(start);
		params2.add(pageSize);
		
		Future<JsonArray> fut1 = MysqlTool.queryJsonArrayFromDb(MysqlClient.getServerPool(), sql1, params1);
		Future<JsonArray> fut2 = MysqlTool.queryJsonArrayFromDb(MysqlClient.getServerPool(), sql2, params2);
		CompositeFuture.all(fut1, fut2).onComplete(res->{
			if (res.succeeded()) {
				JsonObject result = new JsonObject();
				int total = fut1.result().getJsonObject(0).getInteger("total");
				result.put("total", total);
				JsonArray list = fut2.result();
				parseToJson(list);  //解析为json字符串
				result.put("rows",list);
				sendHttpResponse(response, result);
			} else {
				sendHttpResponseError(response,  res.cause().getMessage());
				MainVerticle.logger.error(res.cause().getMessage());
			}
		});
	}
	
	/*
	 * 解析为json字符串
	 */
	private static void parseToJson(JsonArray list) {
		int max = list.size();
		for (int i=0; i<max; i++) {
			JsonObject obj = list.getJsonObject(i);
			int cmdCode = obj.getInteger("cmd_code");
			byte[] requestData = Base64.getDecoder().decode(obj.getBinary("request"));
			byte[] responseData = Base64.getDecoder().decode(obj.getBinary("response"));
			String requestJson = "{}", responseJson = "{}";
			try {
				if (cmdCode > 0 && requestData.length > 0) {
					EnumCmdID eId1 = CmdEnum.EnumCmdID.forNumber(cmdCode);
					String cmdName1 = eId1.name();
					Builder res_build1 = ProtobufManager.getRequestBuild(cmdName1, 1);
					res_build1.mergeFrom(requestData);
					requestJson = JsonFormat.printToString(res_build1.build());
					
					Builder res_build2 = ProtobufManager.getResponseBuild(cmdName1, 1);
					res_build2.mergeFrom(responseData);
					responseJson = JsonFormat.printToString(res_build2.build());
				}
			} catch (InvalidProtocolBufferException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			} finally {
				list.getJsonObject(i).put("request", requestJson);
				list.getJsonObject(i).put("response", responseJson);
			}
		}
	}
}
